package com.exe.rege.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.exe.rege.common.R;
import com.exe.rege.entity.Employee;
import com.exe.rege.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;

/**
 *
 */
@Slf4j
@RestController
@RequestMapping("/employee")
public class EmployeeController {
    @Autowired
    private EmployeeService employeeService;

    /*
        员工登录
    */
    @PostMapping("/login")
    public R<Employee> login(HttpServletRequest request, @RequestBody Employee employee){

       //根据页面提交的密码来加密（md5）
        String password = employee.getPassword();
        password = DigestUtils.md5DigestAsHex(password.getBytes());

        //根据页面提交的userName查询数据库
        LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper<>();
        /*
        * Employee::getUsername 使用含义为：
        *   1、实例化一个Employee对象：Employee employee = new Employee();
        *   2、调用Employee对象的get方法，这里调用的是getUsername
        *
        * queryWrapper.eq：
        *   eq方法相当于赋值“=”，将employee.getUsername()赋值给前面实例化的对象
        * */
        queryWrapper.eq(Employee::getUsername, employee.getUsername());
        Employee emp = employeeService.getOne(queryWrapper);

        //如果没有查到目标，则返回错误
        if (emp == null){
            return R.error("登陆失败");
        }

        //查到了，但是密码不对
        if (!emp.getPassword().equals(password)){
            return R.error("密码错误，登录失败");
        }

        //账号密码全对，但是员工状态是被禁用
        if (emp.getStatus() == 0){
            return R.error("员工已被禁用，登陆失败");
        }

        //登陆成功，将员工id存入session中并返回登陆成功的结果
        request.getSession().setAttribute("employee",emp.getId());
        return R.success(emp);
    }

    /**
     * 员工退出
     * @param request
     * @return
     */
    @PostMapping("/logout")
    public R<String> logout(HttpServletRequest request){
        //清理Session保存的当前登录员工的id
        request.getSession().removeAttribute("employee");
        return R.success("员工退出成功");
    }

    /*
    * 新增员工
    * */
    @PostMapping
    public R<String> add(HttpServletRequest request, @RequestBody Employee employee){
        //先判断是否有账号存在，数据库中查找，如果想要减轻数据库压力，可在全局抛异常
//        LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper<>();
//        queryWrapper.eq(Employee::getUsername, employee.getUsername());
//        Employee emp = employeeService.getOne(queryWrapper);
//        if (emp != null){
//            return R.error("已有此账号，请勿重复添加。");
//        }

        log.info("前端传来的员工信息是：{}",employee.toString());
        //设置初始密码，md5加密
        employee.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));

        //设置了自动补充公共字段就可以把这里注释了
//        employee.setCreateTime(LocalDateTime.now());
//        employee.setUpdateTime(LocalDateTime.now());

        //获取当前登录的人的id,从session里拿，所以要加上HttpServletRequest
//        Long userId = (Long) request.getSession().getAttribute("employee");
//        employee.setCreateUser(userId);
//        employee.setUpdateUser(userId);
        //状态在数据库有默认数值了，不一定自己设置
        employee.setStatus(1);

        employeeService.save(employee);
        return R.success("员工新增成功");
    }

    /*
    * 员工信息分页查询
    * */
    @GetMapping("/page")
    public R<Page> Page(int page, int pageSize, String name){
        log.info("page = {}, pageSize = {}, name = {}",page,pageSize,name);

        //构造分页构造器
        Page pageInfo = new Page(page,pageSize);

        //构造条件构造器
        LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper<>();
        //添加过滤条件，如果name为空就不能用like
        queryWrapper.like(StringUtils.isNotEmpty(name), Employee::getName, name);
        //添加排序条件,orderByDesc降序
        queryWrapper.orderByDesc(Employee::getUpdateTime);

        //执行查询
        employeeService.page(pageInfo, queryWrapper);

        return R.success(pageInfo);
    }

    /*
    * 根据id修改员工信息
    * */
    @PutMapping
    public R<String> update(HttpServletRequest request, @RequestBody Employee employee){
        log.info("修改员工信息：{}",employee.toString());

        //注意：此处传到前端的id太长（Long），前端展示会丢失精度，导致修改后传回来的id有所变化导致修改失败
        //故此需要将Long 转成 Json String，使用到对象映射器，JacksonObjectMapper
//        Long empId = (Long) request.getSession().getAttribute("employee");
//        employee.setUpdateUser(empId);
//        employee.setUpdateTime(LocalDateTime.now());

        employeeService.updateById(employee);
        return R.success("员工信息修改成功");
    }

    /*
    * 通过id获取员工信息
    * 编辑员工信息时，先用id把之前的信息查进去
    * */
    @GetMapping("/{id}")
    public R<Employee> getById(@PathVariable Long id){
        log.info("通过id查询员工信息");
        Employee employee = employeeService.getById(id);

        if (employee != null){
            return R.success(employee);
        }
        return R.error("未查询到此员工信息...");//避免：点编辑的时候有人把该员工信息删除了的情况
    }










}
